##
# Copyright (c) 2006 Patrick J. Leyden III
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
##

from donut_duty import *
from message_duty import *
import cPickle as pickle
from SocketServer import TCPServer, StreamRequestHandler
from mx.DateTime import now, RelativeDateTime, Monday, Thursday, Friday
from threading import *
import sys
from email_duty import *


DATA_FILE_NAME = "duty.data"
NEXT_FRIDAY = RelativeDateTime(days=3, weekday=(Friday, 0))
NEXT_THURSDAY = RelativeDateTime(days=4, weekday=(Thursday, 0))
WEEKDAY_MONDAY = RelativeDateTime(weekday=(Monday, 0))
# Change this at some point.  I should avoid global variables.
groups = None


def log(log_string):
    sys.stdout.write(log_string + "\n")
    sys.stdout.flush()


class DonutDuty(Duty):
    name = "DonutDuty"
    short_desc = "Bring in donuts for the office."
    long_desc = "Bring in donuts and/or bagels on the last day of the" + \
                " work week for the office donut club."
    def __init__(self, time):
        Duty.__init__(self, DonutDuty.name, DonutDuty.short_desc,
            DonutDuty.long_desc, time)
        self.is_monday_reminder_sent = False;
        self.is_day_of_reminder_sent = False;


def simple_duty_assignment(group_id):
    if group_id in groups:
        group = groups[group_id]
        group.add_duty(DonutDuty)
        next_time = now() + NEXT_FRIDAY
        for member in group.members:
            member.assign_duty(DonutDuty(next_time))
            next_time += NEXT_FRIDAY


def print_group(group_id, with_duties = False):
    if group_id in groups:
        group = groups[group_id]
        log("%s:" % group.name)
        for member in group.members:
            log("(%s, %s)" % (member.name, member.email))
            if with_duties:
                for duty in member.duties.itervalues():
                    log("  %s at %s" % (duty.name, duty.time))
    else:
        log("Unknown group \'%s\'" % group_id)
            

def send_reminder(member, duty):
    if isinstance(duty, DonutDuty) and not duty.is_monday_reminder_sent:
        print "Sending Monday reminder to %s for %s." % (member.name, duty.name)
        duty.is_monday_reminder_sent = True;
        send_monday_email(member, duty)
    else:
        print "No reminder for %s" % duty.name


class MessageHandler(StreamRequestHandler):
    def handle(self):
        log("Client connected (%s:%d)." % self.client_address)
        try:
            msg = pickle.load(self.rfile)
            while msg:
                log("%s" % msg)
                if isinstance(msg, CreateGroup) and msg.name not in groups:
                    groups[msg.name] = Group(msg.name)
                elif isinstance(msg, AddMember) and msg.group_id in groups:
                    groups[msg.group_id].add_member(msg.member)
                elif isinstance(msg, PrintMemberList):
                    print_group(msg.group_id, True)
                elif isinstance(msg, AutoAssignDuties):
                    simple_duty_assignment(msg.group_id)
                msg = pickle.load(self.rfile)
        except EOFError:
            log("Client disconnected.")
        except KeyboardInterrupt:
            log("Killed client connection via Keyboard Interrupt.")
            
            
class DutyWatchThread(Thread):
    def __init__(self):
        Thread.__init__(self, name="DutyWatch")
        self.setDaemon(True)
        
    def run(self):
        import time
        time.sleep(3)
        while 1:
            self.do_stuff()
            time.sleep(10)

    def do_stuff(self):
        current_time = now()
        print "Doing stuff at %s..." % current_time
        for group in groups.itervalues():
            for member in group.members:
                for duty in member.duties.itervalues():
                    monday_reminder = duty.time + WEEKDAY_MONDAY
                    if monday_reminder < current_time:
                        log("Time for %s to perform %s." %
                            (member.name, duty.name))
                        send_reminder(member, duty)
        try:
            print "Saving group data..."
            data_file = file(DATA_FILE_NAME, "wb")
            pickle.dump(groups, data_file, PICKLE_LEVEL)
        except IOError:
            print "Failed to save group data!"


if __name__ == "__main__":
    groups = {}
    # Read saved date.
    try:
        data_file = file(DATA_FILE_NAME, "rb")
        groups = pickle.load(data_file)
        #groups[group.name] = group
    except IOError:
        pass
    #
    # Print the contents of the data file.
    log("Current group database:")
    for group in groups.itervalues():
        log("%s:" % group.name)
        for member in group.members:
            log("(%s, %s)" % (member.name, member.email))
    #
    # Create the duty watch thread.
    duty_watch = DutyWatchThread()
    duty_watch.start()
    #
    # Setup the socket server and listen forever.
    stream_server = TCPServer(('localhost', DEFAULT_PORT), MessageHandler)
    log("Serving socket forever...")
    try:
        stream_server.serve_forever()
    except KeyboardInterrupt:
        log("Exiting...")
